<!-- 商品设置 -->
<template>
    <div >
        <a-page-header
            style="border: 1px solid rgb(235, 237, 240);background:#fff"
            :title="`商品-${goods.name}-入库设置`"
            @back="() => $router.go(-1)"
        >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <!-- <a-col :md="8" :sm="24">
                        <a-form-item label="商品名称">
                            <a-input v-model="goodsName" allow-clear placeholder="请输入商品名称" />
                        </a-form-item>
                    </a-col> -->
                    <a-col :md="8" :sm="24">
                        <a-form-item label="颜色">
                            <a-select v-model="colorId" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in colorsList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="等级">
                            <a-select v-model="grade" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in gradeList" :key="i" :value="item.name">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="规格">
                            <a-select v-model="spec" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in specList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="状态">
                            <a-select v-model="status" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button style="margin-right: 20px" type="primary" @click="getData()">查询</a-button>
                            <a-button icon="plus" @click="add()">公共区二级新增</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  
        <a-table size="small" :columns="columns" :data-source="dataList" :loading="isload" @change="handleTableChange" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size}" border>
            <div slot="imageUrl" slot-scope="imageUrl">
                <img v-if="imageUrl && imageUrl != ''" style="width: 100px;height: 50px" :src="imageUrl" alt="">
                <div v-else>-</div>
            </div>
            <div slot="grade" slot-scope="grade,record" @dblclick="iptdbclick(record,'grade')">
                <a-select v-if="updateId == record.id && upType == 'grade'" v-model="upValue" placeholder="请选择" @change="iptUpdate">
                    <a-select-option v-for="(item) in gradeList" :value="item.name" :key="item.id">{{item.name}}</a-select-option>
                </a-select>    
                <div v-else v-for="(item,i) in gradeList" :key="i">
                    <a-tag v-if="item.name == grade" :color="colors[i%13]">{{item.name}} </a-tag>
                </div>
            </div>
            <div slot="specId" slot-scope="specId,record" @dblclick="iptdbclick(record,'specId')">
                <a-select v-if="updateId == record.id && upType == 'specId'" v-model="upValue" placeholder="请选择" @change="iptUpdate">
                    <a-select-option v-for="(item) in specList" :value="item.id.toString()" :key="item.id">{{item.name}}</a-select-option>
                </a-select>    
                <div v-else v-for="(item,i) in specList" :key="i">
                    <a-tag v-if="item.id == specId" :color="colors[i%13]">{{item.name}} </a-tag>
                </div>
            </div>
            <div slot="colorId" slot-scope="colorId,record" @dblclick="iptdbclick(record,'colorId')">
                <a-select v-if="updateId == record.id && upType == 'colorId'" v-model="upValue" placeholder="请选择" @change="iptUpdate">
                    <a-select-option v-for="(item) in colorsList" :value="item.id.toString()" :key="item.id">{{item.name}}</a-select-option>
                </a-select>    
                <div v-else v-for="(item,i) in colorsList" :key="i">
                    <a-tag v-if="item.id == colorId" :color="colors[i%13]">{{item.name}} </a-tag>
                </div>
            </div>
            <div slot="description" slot-scope="description,record" @dblclick="iptdbclick(record,'description')">
                <a-select v-if="updateId == record.id && upType == 'description'" v-model="upValue" placeholder="请选择" @change="iptUpdate">
                    <a-select-option v-for="(item) in descriptionList" :value="item.name" :key="item.id">{{item.name}}</a-select-option>
                </a-select>    
                <div v-else>{{description}}</div>
            </div>
            <div slot="flowerPattern" slot-scope="flowerPattern,record" @dblclick="iptdbclick(record,'flowerPattern')">
                <a-select v-if="updateId == record.id && upType == 'flowerPattern'" v-model="upValue" placeholder="请选择" @change="iptUpdate">
                    <a-select-option v-for="(item) in flowerPatternList" :value="item.name" :key="item.id">{{item.name}}</a-select-option>
                </a-select>    
                <div v-else>{{flowerPattern}}</div>
            </div>
            <div slot="remarks" slot-scope="remarks,record" @dblclick="iptdbclick(record,'remarks')">
                <a-select v-if="updateId == record.id && upType == 'remarks'" v-model="upValue" placeholder="请选择" @change="iptUpdate">
                    <a-select-option v-for="(item) in remarkList" :value="item.name" :key="item.id">{{item.name}}</a-select-option>
                </a-select>    
                <div v-else>{{remarks}}</div>
            </div>
            <div slot="notes" slot-scope="notes">
                <Ellipsis :length="18" tooltip >{{notes ? notes : '-'}}</Ellipsis>
            </div>
            <div slot="status" slot-scope="status">
                <a-switch checked-children="上架" un-checked-children="下架" disabled :checked="status == 1 ? true : false" />
            </div>
            <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="update(record)">修改</a-button>
                    <a-popconfirm
                        title="是否确认删除当前数据?"
                        ok-text="Yes"
                        cancel-text="No"
                        @confirm="del(record)"
                    >
                        <a-button class="errorColor" type="link">删除</a-button>
                    </a-popconfirm>
                </div>
            </template>
        </a-table>
        </a-page-header>

        <!-- 增删改商品设置 -->
        <a-modal
            title="添加、修改上架商品信息"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="商品等级" >
                        <div style="display: flex">
                            <a-select show-search v-model="item.grade" placeholder="请选择" v-if="gradeSel">
                                <a-select-option v-for="(itm) in gradeList" :value="itm.name" :key="itm.id">{{itm.name}}</a-select-option>
                            </a-select>   
                            <a-input v-else v-model="item.grade" :placeholder="`请输入商品等级`" allow-clear></a-input>
                            <a-button style="margin-left: 20px;" @click="gradeSel = !gradeSel" :type="gradeSel ? 'primary' : 'danger'">{{gradeSel ? '默认' : '恢复'}}</a-button>
                        </div>
                    </a-form-item>
                    <a-form-item label="商品颜色">
                        <a-select show-search  v-model="item.colorId" placeholder="请选择">
                            <a-select-option v-for="(itm) in colorsList" :value="itm.name +',' +itm.id" :key="itm.id">{{itm.name}}</a-select-option>
                        </a-select>       
                    </a-form-item>
                    <a-form-item label="周期" >
                        <a-select show-search  v-model="item.specId" placeholder="请选择">
                            <a-select-option v-for="(itm) in specList" :value="itm.name +',' +itm.id" :key="itm.id">{{itm.name}}</a-select-option>
                        </a-select>   
                    </a-form-item>
                    <a-form-item label="销售价上浮" >
                        <a-input v-model="item.spFloatRatio" :placeholder="`请输入销售价上浮比例`" suffix="%" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="原价上浮" >
                        <a-input v-model="item.opFloatRatio" :placeholder="`请输入原价上浮比例`" suffix="%" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="商品花型">   
                        <div style="display: flex">
                            <a-select show-search v-model="item.flowerPattern" placeholder="请选择" v-if="flowerSel">
                                <a-select-option v-for="(itm) in flowerPatternList" :value="itm.name" :key="itm.id">{{itm.name}}</a-select-option>
                            </a-select>  
                            <a-input v-else v-model="item.flowerPattern" :placeholder="`请输入商品等级`" allow-clear></a-input>
                            <a-button style="margin-left: 20px;" @click="flowerSel = !flowerSel" :type="flowerSel ? 'primary' : 'danger'">{{flowerSel ? '默认' : '恢复'}}</a-button>
                        </div>  
                    </a-form-item>
                    <a-form-item label="枝干">
                        <div style="display: flex">
                            <a-select show-search v-model="item.description" placeholder="请选择" v-if="descSel">
                                <a-select-option v-for="(itm) in descriptionList" :value="itm.name" :key="itm.id">{{itm.name}}</a-select-option>
                            </a-select>   
                            <a-input v-else v-model="item.description" :placeholder="`请输入商品等级`" allow-clear></a-input>
                            <a-button style="margin-left: 20px;" @click="descSel = !descSel" :type="descSel ? 'primary' : 'danger'">{{descSel ? '默认' : '恢复'}}</a-button>
                        </div>     
                    </a-form-item>
                    <a-form-item label="单位">
                        <div style="display: flex">
                            <a-select show-search v-model="item.remarks" placeholder="请选择" v-if="remarkSel">
                                <a-select-option v-for="(itm) in remarkList" :value="itm.name" :key="itm.id">{{itm.name}}</a-select-option>
                            </a-select>  
                            <a-input v-else v-model="item.remarks" :placeholder="`请输入商品等级`" allow-clear></a-input>
                            <a-button style="margin-left: 20px;" @click="remarkSel = !remarkSel" :type="remarkSel ? 'primary' : 'danger'">{{remarkSel ? '默认' : '恢复'}}</a-button>
                        </div>     
                    </a-form-item>
                    <a-form-item label="商品备注" >
                        <a-input v-model="item.notes" :placeholder="`请输入商品备注信息`" allow-clear ></a-input>
                    </a-form-item>
                    <a-form-item label="图片">
                        <a-tag color="#f50">
                            修改时，如果上传图片就会覆盖掉之前的图片，如果不修改就无需上传
                        </a-tag>
                        <div class="clearfix">
                            <a-upload
                            list-type="picture-card"
                            :file-list="fileList"
                            
                            @change="handleChange"
                            >
                            <div v-if="fileList.length < 1">
                                <a-icon type="plus" />
                                <div class="ant-upload-text">
                                    选择图片
                                </div>
                            </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="是否上架">
                        <a-radio-group v-model="item.status" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { queryClassify } from '@/api/mall/classify';
import { queryGoodsGeneral , queryGoodsCommonConfig , queryGoodsDetail , updateGoodsDetail } from '@/api/newMall';
import moment from 'moment';
import { Ellipsis } from '@/components';
export default {
    components: {
        Ellipsis,
    },
    data () {
        return {
            brandId: this.global.brandId,
            colorId: undefined, // 颜色ID
            goodsId: JSON.parse(this.$route.query.item).id,
            goods: JSON.parse(this.$route.query.item),
            colorsList: [], // 颜色列表
            goodsName: '', // 商品名称
            grade: undefined,
            gradeList: [],
            specList: [],
            descriptionList: [], // 说明列表
            spec: undefined,
            remarkList: [], // 备注列表
            flowerPatternList: [], // 花型列表
            status: undefined,
            statusList: [
                { id: '0', name: '下架'},
                { id: '1', name: '上架'},
            ],
            isSeckillList: [
                { id: '0', name: '否'},
                { id: '1', name: '是'},
            ],
            page: 1,
            size: 10,
            total: 0,
            dataList: [],
            isload: false,
            confirmLoading: false,
            visible: false,
            columns,
            item: {
                id: '',
                goodsId: undefined, // 商品设置信息
                colorId: undefined, // 颜色ID
                grade: undefined, // 商品等级
                specId: undefined, // 商品规格
                opFloatRatio: '', // 原价浮动比例
                spFloatRatio: '', // 售价上浮比例
                notes: '', // 商品备注信息
                description: undefined, // 描述
                remarks: undefined, // 备注
                flowerPattern: undefined, // 花型
                status: '1', // 状态，1：上架，0：下架
            },
            fileList: [],
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            updateId: '',
            upType: '',
            rangePicker: [],
            gradeSel: true,
            flowerSel: true,
            descSel: true,
            remarkSel: true,
        };
    },
    async created(){
        try {
            // await this.getClassify();
            await this.getColors();
            // await this.getArea();
            // await this.getStoreHouse();
            await this.getDescription('3');
            await this.getDescription('4');
            await this.getDescription('5');
            await this.getDescription('6');
            await this.getDescription('7');
            this.getData();
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: error,
                duration: 8,
            })
        }
    },
    methods: {
        moment,
        // 获取商品设置
        getData(){
            let _this = this;
            console.log(_this.page,'page')
            const params = {
                'brandId': _this.brandId,
                'goodsName': _this.goodsName,
                'goodsId': _this.goodsId,
                'colorId': _this.colorId,
                'grade': _this.grade,
                'specId': _this.spec,
                'status': _this.status,
                'page': _this.page - 1,
                'size': _this.size,
            }
            _this.isload = true;
            queryGoodsDetail(params)
            .then(res => {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data.content;
                    _this.total = res.data.totalElements
                    console.log(_this.dataList,'datalIST')
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 获取分类信息
        async getClassify(){
            let _this = this;
            try {
                const params = {
                    'brandId':_this.brandId,
                    'parentId':'0',
                    'size': 99,
                    'page': 0,
                }
                _this.classifyList = await _this._queryClassify(params);
            } catch (error) {
                _this.$notification['error']({
                    message: '提示',
                    description: error,
                    duration: 8,
                })
            }
        },
        _queryClassify(params,type){
            var _this=this
            return new Promise((resolve,reject) => {
                queryClassify(params)
                .then(res=>{
                    if(res.success){
                        resolve(res.data.content)
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 获取颜色信息
        getColors(){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId':_this.brandId,
                    'page': 0,
                    'size': 99,
                    'type': '2',
                };
                queryGoodsCommonConfig(params)
                .then(res=>{
                    if(res.success){
                        _this.colorsList = res.data.content;
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 获取商品说明和备注
        getDescription(type){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId':_this.brandId,
                    'type': type,
                    'page': 0,
                    'size': 99,
                };
                queryGoodsCommonConfig(params)
                .then(res=>{
                    if(res.success){
                        if(type == '3'){
                            _this.gradeList = res.data.content;
                        }else if(type == '4'){
                            _this.specList = res.data.content;
                        }else if(type == '5'){
                            _this.descriptionList = res.data.content;
                        }else if(type == '7'){
                            _this.flowerPatternList = res.data.content;
                        }else{
                            _this.remarkList = res.data.content;
                        }
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加
        add(){
            this.item.id = ''
            this.item.goodsId = undefined
            // this.item.storehouseId = undefined;
            // this.item.areaId = undefined;
            this.item.grade = undefined;
            this.item.colorId = undefined;
            this.item.specId = undefined;
            this.item.opFloatRatio = '';
            this.item.spFloatRatio = '';
            this.item.description = undefined;
            this.item.remarks = undefined;
            this.item.status = '1';
            this.item.notes = '';
            this.fileList = [];
            this.rangePicker = [];
            this.visible = true;
        },
        // 修改
        update(item){
            this.item = JSON.parse(JSON.stringify(item))
            this.item.specId = item.specName + ',' + item.specId
            this.item.colorId = item.colorName + ',' + item.colorId
            this.item.opFloatRatio = item.opFloatRatio * 100;
            this.item.spFloatRatio = item.spFloatRatio * 100;
            this.fileList = [];
            this.visible = true;
        },
        // 选择图片
        handleChange({ fileList }) {
            this.fileList = fileList;
        },
        // 确定添加、修改
        handleOk(){
            let _this = this
            _this.confirmLoading = true
            if(_this.item.colorId === undefined){
                _this.$message.warning('请选择商品颜色');
                return
            }
            if(_this.item.grade === undefined){
                _this.$message.warning('请选择商品等级信息');
                return
            }
            if(_this.item.specId === undefined){
                _this.$message.warning('请选择商品规格信息');
                return
            }
            // if(_this.item.opFloatRatio === ''){
            //     _this.$message.warning('请输入商品原价浮动比例');
            //     return
            // }
            // if(_this.item.spFloatRatio === ''){
            //     _this.$message.warning('请输入商品售价浮动比例');
            //     return
            // }
            if(_this.item.description === undefined){
                _this.$message.warning('请选择商品描述信息');
                return
            }
            if(_this.item.remarks === undefined){
                _this.$message.warning('请选择商品备注信息');
                return
            }
            if(_this.item.flowerPattern === undefined){
                _this.$message.warning('请选择商品花型信息');
                return
            }
            // if(_this.item.id == '' && _this.fileList.length == 0){
            //     _this.$message.warning('请选择商品图片');
            //     return
            // }
            _this.confirmLoading = true;
            var formData = new FormData();
            formData.append('brandId', _this.brandId);
            formData.append('id', _this.item.id);
            formData.append('goodsId', _this.goodsId);
            formData.append('colorId', _this.item.colorId.split(',')[1]);
            formData.append('specId', _this.item.specId.split(',')[1]);
            formData.append('grade', _this.item.grade);
            formData.append('opFloatRatio', _this.item.opFloatRatio / 100);
            formData.append('spFloatRatio', _this.item.spFloatRatio / 100);
            formData.append('description', _this.item.description);
            formData.append('remarks', _this.item.remarks);
            formData.append('notes', _this.item.notes.replace(/----/g,'--').replace(/---/g,'--'));
            formData.append('flowerPattern', _this.item.flowerPattern);
            formData.append('status', _this.item.status);
            if(_this.fileList.length > 0){
                formData.append('file',_this.fileList[0].originFileObj)
            }
            updateGoodsDetail(formData)
            .then(res=>{
                _this.confirmLoading = false
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.item.id == '' ? '添加成功' : '修改成功',
                        duration: 8,
                    })
                    _this.visible = false
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 删除
        del(item){
            let _this = this;
            const params = {
                'id': item.id,
                'name': item.name,
                'cateId': item.cateId,
                'isDelete': '1'
            }
            var formData = new FormData();
            formData.append('brandId', _this.brandId);
            formData.append('id', item.id);
            formData.append('grade', item.grade);
            formData.append('status', item.status);
            formData.append('isDelete', '1');
            updateGoodsDetail(formData)
            .then(res => {
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        iptdbclick(item,type){
            console.log('触发双击',type)
            this.updateId = item.id;
            this.upValue = item[type];
            this.upType = type;
            this.item = item;
            console.log(this.upValue,'upvalue')
        },
        iptUpdate(type){
            console.log(this.dataList,'datalist')
            console.log(this.upValue,'upValue')
            this.updateId = ''
            this.iptUpdateEvent(this.item)
        },
        // 修改数据
        iptUpdateEvent(item){
            let _this = this;
            const formData = new FormData();
            if(this.upValue === '' || this.upValue === undefined){
                return;
            }
            formData.append('id', item.id);
            formData.append(this.upType,this.upValue)
            updateGoodsDetail(formData)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '修改成功',
                        duration: 8,
                    })
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        seckillTimeChange(value, dateString) {
            if(dateString[0]){
                this.item.seckillStartTime = dateString[0];
                this.item.seckillEndTime = dateString[1];
            }else{
                this.item.seckillStartTime = '';
                this.item.seckillEndTime = '';
            }
        },
        seckillTimeOk(value) {
            console.log(this.rangePicker,'datestring')
            if(this.rangePicker[0]){
                this.item.seckillStartTime = moment(value[0]).format('YYYY-MM-DD hh:mm:ss');
                this.item.seckillEndTime = moment(value[1]).format('YYYY-MM-DD hh:mm:ss');
            }else{
                this.item.seckillStartTime = '';
                this.item.seckillEndTime = '';
            }
        },
    }
}

</script>
<style scoped>

</style>